#dict that returns None for d[k] when k is not in d
class adict(dict):
    def __missing__(self, k):
        return None


def pargs(args):
    '''for structuring command line arguments
        --------------------
        usage:
            import sys, argpar
            d = argpar.pargs(sys.argv)
         puts arguments in a dictionary d such that d[0] = path, d[1] =  list of arguments preceding the first dash-prefixed argument,
             and for each dash-prefixed argument k, d[k] = list of k and  arguments following k & preceding the next dash-prefixed argument;
        dashes are stripped from dictionary keys
         "\"-prefixed arguments are stripped of their leading "\" (can be  used to escape leading dashes; at most one "\" will be stripped)
        upon lookup of a key not in the dictionary, the dictionary returns None rather than throwing a key error
        --------------------
        given string list args = [path?, arg1* as simple_arg, arg2* as keyed_arg],
            where simple_arg is a string that does not start with "-"
            and keyed_arg = k as key_arg, v* as simple_arg
                where key_arg is a string that starts with "-"
        returns adict{0:path|None, 1:[foo(arg1)*], bar(arg2.k):[foo(arg2.k)]+arg2.[foo(v)*],... for all arg2}
            where foo(x) returns x without leading "\" (x without change if no leading "\")
            and bar(x) returns x without leading "-" '''
    d = adict()
    arlen = len(args)
    if arlen < 1:
        args = [None]
        arlen = 1
    d[0] = args[0]
    lastkeyindex = 1
    lastkey = 1
    for i in range(1, arlen+1):
        if i >= arlen or args[i][:1] == '-':
            d[lastkey] = args[lastkeyindex:i]
            lastkeyindex = i
            lastkey = args[i][1:] if i < arlen else None
        elif args[i][:1] == '\\':
            args[i] = args[i][1:]
    return d
    
# def pargs_test():
    # import sys
    # for a in pargs(sys.argv).items():
        # print a        
#pargs_test()